//
//  BasePlayVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/8/26.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "BasePlayVC.h"
#import "IGShare.h"
#import "FeedBackVC.h"
#import "UserSubmitQustionVC.h"
#import "JMHoledView.h"
#import "UserCommentsVC.h"
#import "TabItem.h"
@interface BasePlayVC ()

@property (nonatomic, strong)UIButton * moreBtn;

@property (nonatomic, strong)UIButton * shareBtn;

@property (weak, nonatomic) IBOutlet UIButton *submitQuestionBtn;

@property (nonatomic,strong) UISwitch * loopSwith;

@property (nonatomic,strong) UISwitch * automaticSwith;

@property (nonatomic,strong) UIView*  menuView;

@property (nonatomic, strong) UIView * foldBtn;

@property (nonatomic, strong) UILabel * foldTitleLabel;

@property (nonatomic, strong) UIImageView * foldIcon;
@end

@implementation BasePlayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    [self rightBarButtonWithImageName:@"分享" selector:@selector(showShareSheet:)];
    
    [self leftBarButton1WithImageName:@"back" selector1:@selector(backAction) button2ImageName:@"回到首页" selector2:@selector(goHome)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.shareBtn];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self newGuidePage];
    });
}

- (UIButton *)shareBtn {
    
    if (!_shareBtn) {
        _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shareBtn setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
        [_shareBtn sizeToFit];
        [_shareBtn addTarget:self action:@selector(showShareSheet:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    _isStraightPlay = NO;
    
}


- (void)setNavGradient {
    
    UIView * navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kNavigationBarHeight)];
    navView.backgroundColor = [UIColor darkTextColor];
    navView.alpha = 0.6;
    [self.view addSubview:navView];

}

- (void)newGuidePage {

    if (self.alert) {
        return;
    }
    
    BOOL hasInPlayer = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasInPlayer"];

    if (hasInPlayer) {
        return;
    }


    //添加遮罩指示
    JMHoledView *holedView = [[JMHoledView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view.window addSubview:holedView];

    //   分享

    CGRect shareRect1 = [self.shareBtn convertRect:self.shareBtn.bounds toView:self.view.window];

    //    [holedView addHoleCircleCenteredOnPosition:CGPointMake(CGRectGetMidX(shareRect1), CGRectGetMidY(rect)) diameter:CGRectGetWidth(rect) - 4];

    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = shareRect1;
    [shareBtn setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];

    [holedView addHCustomView:shareBtn onRect:shareRect1];


    UIImage *shareImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_PLAYER_SHARE", nil)];

    UIImageView *shareImageview = [[UIImageView alloc] initWithImage:shareImage];

    CGRect shareRect = CGRectMake(CGRectGetMinX(shareRect1) - shareImage.size.width - 5, CGRectGetMidY(shareRect1), shareImage.size.width, shareImage.size.height);

    [holedView addHCustomView:shareImageview onRect:shareRect];


//    __block NSInteger clickTimes = 0;

//    @weakify(self);
    [holedView clickedBlock:^(JMHoledView *holedView, NSInteger index) {
//        @strongify(self);
        [holedView removeHoles];
        [holedView removeFromSuperview];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasInPlayer"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        

//        if (clickTimes == 2) {
//            [holedView removeFromSuperview];
//
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasInPlayer"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            return;
//        }
//
//        if (clickTimes == 0) {
//            //   更多
//            CGRect moreRect1 = [self.moreBtn convertRect:self.moreBtn.bounds toView:self.view.window];
//
//            UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//            moreBtn.frame = moreRect1;
//            [moreBtn setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
//
//            [holedView addHCustomView:moreBtn onRect:moreRect1];
//
//
//            UIImage *moreImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_PLAYER_MORE", nil)];
//
//            UIImageView *moreImageview = [[UIImageView alloc] initWithImage:moreImage];
//
//            CGRect moreRect = CGRectMake(CGRectGetMaxX(moreRect1) - moreImage.size.width, CGRectGetMaxY(moreRect1) + 5, moreImage.size.width, moreImage.size.height);
//
//            [holedView addHCustomView:moreImageview onRect:moreRect];
//        } else if (clickTimes == 1) {
//
//            //   提问
//            CGRect askRect1 = [self.submitQuestionBtn convertRect:self.submitQuestionBtn.bounds toView:self.view.window];
//
//            UIButton *askBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//            askBtn.frame = askRect1;
//            [askBtn setImage:[UIImage imageNamed:@"问行家"] forState:UIControlStateNormal];
//
//            [holedView addHCustomView:askBtn onRect:askRect1];
//
//
//            UIImage *askImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_PLAYER_ASK", nil)];
//
//            UIImageView *askImageview = [[UIImageView alloc] initWithImage:askImage];
//
//            CGRect askRect = CGRectMake(CGRectGetMinX(askRect1) - askImage.size.width - 5, CGRectGetMidY(askRect1) - askImage.size.height, askImage.size.width, askImage.size.height);
//
//            [holedView addHCustomView:askImageview onRect:askRect];
//
//        }
//
//        clickTimes ++;
    }];

}



-(UIButton *)moreBtn {
    
    if (!_moreBtn) {
        _moreBtn= [UIButton buttonWithType:UIButtonTypeCustom];
        _moreBtn.frame = CGRectMake(0, 0, 30, 44);
        
        [_moreBtn addTarget:self action:@selector(showMoreMenu:) forControlEvents:UIControlEventTouchUpInside];
        [_moreBtn setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    }
    
    
    return _moreBtn;
}


- (void)goHome {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark  -- 悬浮功能按钮

// 连续播放 switch 开关
- (UISwitch *)loopSwith {
    if (!_loopSwith) {
        _loopSwith = [[UISwitch alloc] init];
        _loopSwith.transform = CGAffineTransformMakeScale(0.6, 0.6);
        [_loopSwith addTarget:self action:@selector(changeSwitchValue:) forControlEvents:(UIControlEventValueChanged)];
        _loopSwith.on = [AppManager sharedManager].allPlayWhenListen;
    }
    
    return _loopSwith;
}

// 自动导览 switch 开关
- (UISwitch *)automaticSwith {
    
    if (!_automaticSwith) {
        _automaticSwith = [[UISwitch alloc] init];
        _automaticSwith.transform = CGAffineTransformMakeScale(0.6, 0.6);
        [_automaticSwith addTarget:self action:@selector(changeSwitchValue:) forControlEvents:(UIControlEventValueChanged)];
        _automaticSwith.on = [AppManager sharedManager].automaticPlay;
    }
    
    return _automaticSwith;
}

// 折叠按钮
- (UIView *)foldBtn {
    
    if (!_foldBtn) {
        _foldBtn = [[UIView alloc] init];
        _foldBtn.backgroundColor = [UIColor whiteColor];
        _foldBtn.layer.cornerRadius = 3;
        _foldBtn.clipsToBounds = YES;
        _foldIcon =[[UIImageView alloc] initWithFrame:CGRectMake(5, 2.5,5, 10)];
        _foldIcon.image = [UIImage imageNamed:@"foldIcon"];
        _foldIcon.contentMode = UIViewContentModeScaleToFill;
        [_foldBtn addSubview:_foldIcon];
        _foldTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,15, 15, 25)];
        _foldTitleLabel.textAlignment = NSTextAlignmentCenter;
        _foldTitleLabel.numberOfLines = 2;
        _foldTitleLabel.textColor = kSubitleColor;
        _foldTitleLabel.font = Font(10);
        _foldTitleLabel.text = MYLocalizedString(@"SITEPLAY_FOLD_OFF", nil);
        [_foldBtn addSubview:_foldTitleLabel];
        
        self.isOpen = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foldBtnClicked:)];
        [_foldBtn addGestureRecognizer:tap];
        
    }
    
    return _foldBtn;
}

- (void)foldBtnClicked:(UITapGestureRecognizer *)tap {
    
    if (self.isOpen) {
        [self off];
    }else {
        
        [self open];
    }
    
}

- (void)open {
    
    self.menuView.hidden = NO;
    self.isOpen = YES;
    _foldTitleLabel.text = MYLocalizedString(@"SITEPLAY_FOLD_OFF", nil);
    _foldIcon.transform = CGAffineTransformIdentity;
}

- (void)off {
    
    self.menuView.hidden = YES;
    self.isOpen = NO;
    _foldTitleLabel.text = MYLocalizedString(@"SITEPLAY_FOLD_ON", nil);
    _foldIcon.transform = CGAffineTransformMakeRotation(M_PI);
    
}
- (UIButton *)getItemWith:(NSDictionary *)dict {
    
    NSNumber * functionName = dict[@"FunctionName"];
    
    UIButton * item = [UIButton buttonWithType:UIButtonTypeCustom];
    item.backgroundColor = [UIColor whiteColor];
    [item setImage:[UIImage imageNamed:dict[@"imageName"]] forState:UIControlStateNormal];
    [item setTitle:MYLocalizedString(dict[@"title"], nil) forState:UIControlStateNormal];
    [item setTitleColor:kContentColor forState:UIControlStateNormal];
    item.titleLabel.font = Font(8);
    item.tag = functionName.integerValue;
    item.imageEdgeInsets = UIEdgeInsetsMake(-5, 10, 10, 0);
    item.titleEdgeInsets = UIEdgeInsetsMake(25,-20, 0, 0);
    [item addTarget:self action:@selector(menuBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    return item;
}


- (void)initScenicFunctionItemView{
    NSArray * arr = @[@{@"title":@"SITEPLAY_LOOP_MODE",@"FunctionName":@(PlayFuntionLoopSwith)},@{@"title":@"SITEPLAY_SUBMIT_ASK",@"imageName":@"问行家",@"FunctionName":@(PlayFuntionAsk)},@{@"title":@"SITEPLAY_COMMENT",@"imageName":@"写点评",@"FunctionName":@(PlayFuntionComment)},@{@"title":@"SITEPLAY_FEEDBACK",@"imageName":@"意见反馈",@"FunctionName":@(PlayFuntionFeedback)},@{@"title":@"SITEPLAY_MAP",@"imageName":@"mapMode",@"FunctionName":@(PlayFuntionChangeMap)}];
    [self createFunctionViewWith:arr Rect:CGRectMake(SCREEN_WIDTH - 60,kNavigationBarHeight + 10, 62,220)];
}
- (void)initCityTourFunctionItemView{
    NSArray * arr = @[@{@"title":@"CITYTOUR_AUTO_WALK",@"FunctionName":@(PlayFuntionAutomaticSwith)},@{@"title":@"SITEPLAY_LOOP_MODE",@"FunctionName":@(PlayFuntionLoopSwith)},@{@"title":@"SITEPLAY_SUBMIT_ASK",@"imageName":@"问行家",@"FunctionName":@(PlayFuntionAsk)},@{@"title":@"SITEPLAY_COMMENT",@"imageName":@"写点评",@"FunctionName":@(PlayFuntionComment)},@{@"title":@"SITEPLAY_FEEDBACK",@"imageName":@"意见反馈",@"FunctionName":@(PlayFuntionFeedback)}];
    [self createFunctionViewWith:arr Rect:CGRectMake(SCREEN_WIDTH - 60,kNavigationBarHeight + 10, 62, 220)];
}

- (void)createFunctionViewWith:(NSArray *)arr Rect:(CGRect)frame {
    
    UIView * bgView = [[UIView alloc] initWithFrame:frame];
    bgView.backgroundColor = [UIColor clearColor];
    _menuView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, frame.size.height)];
    _menuView.backgroundColor = [UIColor clearColor];
    [bgView addSubview:_menuView];
    
    
    CGFloat W = 42;
    CGFloat H = 44;
    CGFloat space = 0;
    
    for (int i = 0; i< arr.count; i++) {
        
        NSDictionary * dict = arr[i];
        NSNumber * functionName = dict[@"FunctionName"];
        if (functionName.integerValue == PlayFuntionLoopSwith) {
            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, i*H, W, H)];
            view.backgroundColor = [UIColor whiteColor];
            self.loopSwith.frame = CGRectMake(5, 5, 20, 20);
            [view addSubview:self.loopSwith];
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 24, W, 20)];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = kContentColor;
            label.text = MYLocalizedString(dict[@"title"], nil) ;
            label.font = Font(8);
            [view addSubview:label];
            [_menuView addSubview:view];
        }else if(functionName.integerValue == PlayFuntionAutomaticSwith){
            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, i*H, W, H)];
            view.backgroundColor = [UIColor whiteColor];
            self.automaticSwith.frame = CGRectMake(5, 5, 20, 20);
            [view addSubview:self.automaticSwith];
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 24, W, 20)];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = kContentColor;
            label.text = MYLocalizedString(dict[@"title"], nil) ;
            label.font = Font(8);
            [view addSubview:label];
            [_menuView addSubview:view];
        }else {
            UIButton * item = [self getItemWith:dict];
            if (functionName.integerValue == PlayFuntionComment) {
                self.commentBtn = item;
            }else if (functionName.integerValue == PlayFuntionAsk) {
                self.questionBtn = item;
            }else if (functionName.integerValue == PlayFuntionChangeMap){
                self.changeMapBtn = item;
                self.changeMapBtn.hidden = YES;
                [self.changeMapBtn setImage:[UIImage imageNamed:@"PictureMode"] forState:UIControlStateSelected];
            }
            item.frame = CGRectMake(0, i*H + space, W, H);
            [_menuView addSubview:item];
        }
        
        if (i<arr.count) {
            UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, H * i + space, 40, 0.5)];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [_menuView addSubview:lineView];
        }
    }
    
    self.foldBtn.frame = CGRectMake(45, 2, 15, 40);
    [bgView addSubview:self.foldBtn];
    [self.view addSubview:bgView];
}

- (void)changeSwitchValue:(UISwitch *)sender {
    
    if (sender == self.loopSwith) {
        if (sender.on && [AppManager sharedManager].automaticPlay) {
            
            self.automaticSwith.on = NO;
            [AppManager sharedManager].automaticPlay = NO;
        }
        [AppManager sharedManager].allPlayWhenListen = sender.on;
    }else if(sender == self.automaticSwith){
        
        if (sender.on && [AppManager sharedManager].allPlayWhenListen) {
            self.loopSwith.on = NO;
            [AppManager sharedManager].allPlayWhenListen = NO;
        }
        [AppManager sharedManager].automaticPlay = sender.on;
    }
}

- (void)menuBtnClicked:(UIButton *)btn {
    
    IGLog(@"%ld",btn.tag);
    switch (btn.tag) {
        case PlayFuntionAsk:
        {
            [self submitQuestion];
        }
            break;
        case PlayFuntionComment:
        {
            [self comment];
        }
            break;
        case PlayFuntionFeedback:
        {
            [self feedBack];
        }
            break;
        case PlayFuntionChangeMap:
        {
            [self changeMapMode:btn];
        }
            break;
            
        default:
            break;
    }
}

- (void)changeMapMode:(UIButton *)sender {
    
}
#pragma mark -- 分享初始化



- (void)showShareSheet:(UIButton *)sender {
    
    [self.popMenu hideWithAnimation:YES];
    [self popSheet];
}


- (void)showMoreMenu:(UIButton *)sender {
    
    
    if (![self.view viewWithTag:666]) {
        
        if (self.lineModel.hasscore.integerValue > 0) {
            self.popMenu.isCommented = YES;
        }
        [self.popMenu showWithSuperView:self.view];
        
        [self.popMenu dismissHandler:^(BOOL isCanceled, NSInteger row) {
            
            switch (row) {
                case 0:
                    
                    [AppManager sharedManager].allPlayWhenListen = ![AppManager sharedManager].allPlayWhenListen;
                    break;
                case 1:
                    [self comment];
                    break;
                case 2:
                    [self feedBack];
                    break;
                case 3:
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    break;
                    
                    
                default:
                    break;
            }
        }];
    }else {
        
        [self.popMenu hideWithAnimation:YES];
        
    }
}

//- (IBAction)submitQuestion:(id)sender {
//    self.isStraightPlay = YES;
//    if (![UserManager sharedManager].token) {
//
//        [self goLogin];
//        return;
//    }
//
//    UserSubmitQustionVC *questionVC = [[UserSubmitQustionVC alloc] init];
//
//    questionVC.lineModel = self.lineModel;
//
//
//    [self.navigationController pushViewController:questionVC animated:YES];
//}

- (void)submitQuestion{
    
    self.isStraightPlay = YES;
    if (![UserManager sharedManager].token) {
        
        [self goLogin];
        return;
    }
    
    UserSubmitQustionVC *questionVC = [[UserSubmitQustionVC alloc] init];
    
    questionVC.lineModel = self.lineModel;
    
    
    [self.navigationController pushViewController:questionVC animated:YES];
}

- (void)feedBack {
    
    //将我们的storyBoard实例化，“Main”为StoryBoard的名称
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Account" bundle:nil];
    
    
    FeedBackVC *vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"FeedBackVC"];
    
    self.isStraightPlay = YES;
    //跳转事件
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

- (void)comment{
    
    [MobClick event:@"7_0_7"];
    
    self.isStraightPlay = YES;
    
    if (![UserManager sharedManager].token) {
        
        [self goLogin];
        return;
    }
    
    // if (self.lineModel.bought) {
    RatingVC *rateVC = [RatingVC new];
    if (self.lineModel.hasscore.integerValue >0) {
        //        rateVC.hasscore = self.lineModel.hasscore.integerValue;
        //        rateVC.comment = self.lineModel.comment;
        
        UserCommentsVC * commentVC = [[UserCommentsVC alloc] init];
        
        commentVC.lineID = self.lineModel.lineid;
        [self.navigationController pushViewController:commentVC animated:YES];
    }else {
        
        [rateVC show:self completeBlock:^(CGFloat score, NSString *comment) {
            
            [NetAPIManager evaluate:self.lineModel.lineid score:@(score) comment:comment Block:^(NSString *result, NSError *error) {
                
                if (!error) {
                    self.lineModel.hasscore = [NSString stringWithFormat:@"%f",score];
                    self.lineModel.comment = comment;
                    [IGUtils showToast:MYLocalizedString(@"COMMENT_SUCCESS", nil)];
                    
                    __block LineModel *dbModel = nil;
                    
                    [DownloadListDAO getLineModelWithUnionid:self.lineModel.unionid Block:^(LineModel *lineModel) {
                        
                        dbModel = lineModel;
                    }];
                    
                    if (dbModel) {
                        [DownloadListDAO insertLineModel:self.lineModel];
                    }
                    
                }
                
            }];
        }];
    }
}

- (void)goLogin {
    
    LoginVC *loginVC = [LoginVC new];
    loginVC.delegate = self;
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    _isStraightPlay = YES;
    [self presentViewController:nav animated:YES completion:nil];
}


#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    NSString * descrbe = self.lineModel.type.integerValue == 1 ?MYLocalizedString(@"SHARE_LINE_MESSAGE", nil): MYLocalizedString(@"SHARE_SCENIC_MESSAGE", nil);
    
    @weakify(self)
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        @strongify(self)
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:[NSString stringWithFormat:@"fxh5customline/%@",self.lineModel.lineid] title:self.lineModel.linename descr:descrbe thumImage:self.lineModel.pictures object:self.lineModel.playpath type:2 completion:^(id result, NSError *error) {
            
        }];
    };
    [self.sl_popupController dismiss];
}

@end

